package com.chitang.client;

import com.chitang.handler.ClientWebsocketHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @Author: wjs
 * @CreateTime: 2023-03-10 14:09
 */
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 因为是基于http协议的，使用http的编解码器
        pipeline.addLast(new HttpClientCodec());
        // 以块的方式写，添加ChunkedWriteHandler
        pipeline.addLast(new ChunkedWriteHandler());
        /**
         * http数据再传输的过程中是分段的，HttpObjectAggregator就是将多个段聚合
         * 这就是为什么，当浏览器发送大量数据时，会发出多次http请求
         */
        pipeline.addLast(new HttpObjectAggregator(8192));
        // 添加自定义handler
        pipeline.addLast("clientWebsocketHandler", new ClientWebsocketHandler(new NettyClient()));
    }
}
